package com.guisu.material.rv2

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding

/**
 * @dsc     简介
 * @Author  LiWeiZhong
 * @Date    2025/1/20 10:18
 * @Version 1.0
 */
abstract class BaseAdapter<T, VB: ViewBinding>: RecyclerView.Adapter<BaseAdapter<T, VB>.Holder>() {

    protected val TAG = javaClass.simpleName
    private val mData: MutableList<T> = arrayListOf()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
        val inflate = LayoutInflater.from(parent.context)
        return Holder(getVB(inflate, parent))
    }

    override fun onBindViewHolder(holder: Holder, position: Int) {
        onBindHolder(holder, position)
    }

    override fun getItemCount(): Int {
        return mData.size
    }

    abstract fun getVB(inflater: LayoutInflater, parent: ViewGroup): VB
    abstract fun onBindHolder(holder: Holder, position: Int)

    var data: MutableList<T>
        get() = mData
        set(value) {
            val itemCount = mData.size
            mData.clear()
            notifyItemRangeRemoved(0, itemCount)
            mData.addAll(value)
            notifyItemRangeInserted(0, value.size)
        }

    fun getData(position: Int): T {
        return mData[position]
    }

    fun addData(data: MutableList<T>) {
        val positionStart = mData.size
        mData.addAll(data)
        notifyItemRangeInserted(positionStart, data.size)
    }

    fun insertData(data: T?) {
        if (data == null) return
        val position = mData.size
        mData.add(data)
        notifyItemInserted(position)
    }

    fun getPosition(data: T): Int {
        return mData.indexOf(data)
    }

    fun clear() {
        val itemCount = mData.size
        mData.clear()
        notifyItemRangeRemoved(0, itemCount)
    }

    inner class Holder(binding: VB): RecyclerView.ViewHolder(binding.root) {
        val mBinding: VB = binding

        init {
            addEventListener(this)
        }
    }

    abstract fun addEventListener(holder: Holder)
}